package com.google.code.gaestats;

import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;
import com.googlecode.objectify.ObjectifyFactory;
import com.googlecode.objectify.impl.translate.opt.joda.JodaTimeTranslators;

/**
 *
 * @author JaggardM
 */
public class StatsObjectifyFactory
{

	private static final ObjectifyFactory fact = new ObjectifyFactory();
	private static final ThreadLocal<StatsObjectify> instances = new ThreadLocal<StatsObjectify>();
	private static final ThreadLocal<MemcacheService> mss = new ThreadLocal<MemcacheService>();

	static
	{
		JodaTimeTranslators.add(fact);
		fact.register(CounterNames.class);
		fact.register(Counter.class);
		fact.register(HitCounter.class);
		fact.register(ValuedCounter.class);
		fact.register(CounterData.class);
		fact.register(PerMinuteCounterData.class);
		fact.register(PerHourCounterData.class);
	}

	private StatsObjectifyFactory()
	{
	}

	public static MemcacheService ms()
	{
		MemcacheService ms = mss.get();
		if (ms == null)
		{
			ms = MemcacheServiceFactory.getMemcacheService(StatsObjectify.NAMESPACE);
			mss.set(ms);
		}
		return ms;
	}

	public static StatsObjectify ofy()
	{
		StatsObjectify ofy = instances.get();
		if (ofy == null)
		{
			ofy = new StatsObjectify(fact.begin().cache(true));
			instances.set(ofy);
		}
		return ofy;
	}
}
